<template>
  <div class="parking-usage-list-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><Promotion /></el-icon>
            <span>车位使用记录管理</span>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd" plain>
              <el-icon><Plus /></el-icon>添加使用记录
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0" plain>
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
            <el-button type="success" @click="handleExport" plain>
              <el-icon><Download /></el-icon>导出Excel
            </el-button>
            <el-button type="warning" @click="handleImport" plain>
              <el-icon><Upload /></el-icon>导入Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="illustration-container">
        <img src="https://img.icons8.com/color/96/000000/parking.png" alt="Parking Usage Illustration" class="illustration-image">
        <div class="illustration-text">
          <h3>车位使用记录</h3>
          <p>管理小区车位的租赁、购买和临时使用情况</p>
        </div>
      </div>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属小区">
          <el-select v-model="searchForm.communityId" placeholder="请选择小区" clearable>
            <el-option 
              v-for="item in communities" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="业主姓名">
          <el-input v-model="searchForm.ownerName" placeholder="请输入业主姓名" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        
      </el-form>
      <div class="search-buttons">
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>车位使用记录列表</span>
          <el-tag type="info">共 {{ total }} 条记录</el-tag>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :empty-text="'暂无使用记录数据'"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="id" label="ID" width="60" fixed="left" />
        <el-table-column label="所属小区" width="150">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><House /></el-icon>
              <span>{{ scope.row.communityName || '未知' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="车位编号" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Location /></el-icon>
              <span>{{ scope.row.parkingCode || scope.row.parkingName || '未知' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="车位名称" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Promotion /></el-icon>
              <span>{{ scope.row.parkingName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="业主" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><User /></el-icon>
              <span>{{ scope.row.ownerName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" width="140">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Phone /></el-icon>
              <span>{{ scope.row.ownerPhone }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="车牌号" width="120">
          <template #default="scope">
            <el-tag effect="plain">{{ scope.row.carNumber || '无车辆信息' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="使用类型" width="100">
          <template #default="scope">
            <el-tag :type="getUsageTypeTag(scope.row.usageType)" effect="plain">
              {{ scope.row.usageType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="起始日期" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(scope.row.startDate) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="结束日期" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(scope.row.endDate) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="费用" width="100">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Money /></el-icon>
              <span>¥{{ scope.row.fee }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" width="100">
          <template #default="scope">
            <el-tag :type="getPaymentStatusTag(scope.row.paymentStatus)" effect="plain">
              {{ scope.row.paymentStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)" type="primary" text>
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button size="small" @click="handleDelete(scope.row)" type="danger" text>
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-box">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
          </el-card>

    <!-- 导入Excel对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入Excel" width="500px">
      <div class="import-dialog-content">
        <el-alert
          title="请先下载模板，按照模板格式填写数据后上传"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <div class="template-download">
          <el-button type="primary" @click="downloadTemplate" size="small">
            <el-icon><Download /></el-icon>下载模板
          </el-button>
        </div>
        
        <el-upload
          class="excel-upload"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传xlsx/xls文件</div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="importing">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { 
  Plus, 
  Edit, 
  Delete, 
  Search, 
  House, 
  Promotion, 
  Calendar, 
  User,
  Phone,
  Money,
  Location,
  Download,
  Upload
} from '@element-plus/icons-vue';
import ExcelUtil from '@/utils/ExcelUtil';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

export default {
  name: 'ParkingUsageList',
  components: {
    Plus,
    Edit,
    Delete,
    Search,
    House,
    Promotion,
    Calendar,
    User,
    Phone,
    Money,
    Location,
    Download,
    Upload
  },
  data() {
    return {
      searchForm: {
        communityId: '',
        parkingId: '',
        ownerName: '',
        licensePlate: '',
        usageType: '',
        paymentStatus: ''
      },
      communities: [],
      parkings: [],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      sortField: 'id',
      sortOrder: 'desc',
      importDialogVisible: false,
      fileList: [],
      importing: false,
      exportLoading: false
    };
  },
  created() {
    this.fetchCommunities();
    this.fetchParkingUsages();
  },
  watch: {
    'searchForm.communityId': function(newVal) {
      if (newVal) {
        this.fetchParkingsByCommunityId(newVal);
      } else {
        this.parkings = [];
        this.searchForm.parkingId = '';
      }
    }
  },
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '无';
      const date = new Date(dateString);
      return date.toLocaleDateString();
    },

    // 获取使用类型标签颜色
    getUsageTypeTag(type) {
      switch (type) {
        case '租用': return 'warning';
        case '购买': return 'success';
        case '临时': return 'info';
        default: return '';
      }
    },

    // 获取支付状态标签颜色
    getPaymentStatusTag(status) {
      switch (status) {
        case '已支付': return 'success';
        case '未支付': return 'danger';
        default: return 'info';
      }
    },

    // 获取所有小区
    async fetchCommunities() {
      try {
        this.loading = true;
        const response = await axios.get('/api/communities');
        this.communities = response.data;
      } catch (error) {
        console.error('获取小区列表失败:', error);
        ElMessage.error('获取小区列表失败');
      } finally {
        this.loading = false;
      }
    },

    // 根据小区ID获取车位
    async fetchParkingsByCommunityId(communityId) {
      try {
        this.loading = true;
        const response = await axios.get(`/api/parkings/community/${communityId}`);
        this.parkings = response.data;
      } catch (error) {
        console.error('获取车位列表失败:', error);
        ElMessage.error('获取车位列表失败');
      } finally {
        this.loading = false;
      }
    },

    // 获取车位使用记录
    async fetchParkingUsages() {
      try {
        this.loading = true;
        const params = {
          page: this.currentPage - 1,
          size: this.pageSize,
          sort: `${this.sortField},${this.sortOrder}`
        };
        const response = await axios.get('/api/parking-usages', { params });
        this.tableData = response.data.parkingUsages;
        this.total = response.data.totalItems;
      } catch (error) {
        console.error('获取车位使用记录失败:', error);
        ElMessage.error('获取车位使用记录失败');
      } finally {
        this.loading = false;
      }
    },

    // 搜索车位使用记录
    async searchParkingUsages() {
      try {
        this.loading = true;
        // 构建查询参数
        const params = {
          page: this.currentPage - 1,
          size: this.pageSize,
          sort: `${this.sortField},${this.sortOrder}`
        };
        
        // 添加搜索条件
        if (this.searchForm.communityId) params.communityId = this.searchForm.communityId;
        if (this.searchForm.parkingId) params.parkingId = this.searchForm.parkingId;
        if (this.searchForm.ownerName) params.ownerName = this.searchForm.ownerName;
        if (this.searchForm.licensePlate) params.licensePlate = this.searchForm.licensePlate;
        if (this.searchForm.usageType) params.usageType = this.searchForm.usageType;
        if (this.searchForm.paymentStatus) params.paymentStatus = this.searchForm.paymentStatus;
        
        const response = await axios.get('/api/parking-usages/search', { params });
        this.tableData = response.data.parkingUsages;
        this.total = response.data.totalItems;
      } catch (error) {
        console.error('搜索车位使用记录失败:', error);
        ElMessage.error('搜索车位使用记录失败');
      } finally {
        this.loading = false;
      }
    },

    // 搜索按钮点击事件
    onSearch() {
      this.currentPage = 1;
      this.searchParkingUsages();
    },

    // 重置搜索表单
    resetSearch() {
      this.searchForm = {
        communityId: '',
        parkingId: '',
        ownerName: '',
        licensePlate: '',
        usageType: '',
        paymentStatus: ''
      };
      this.currentPage = 1;
      this.fetchParkingUsages();
    },

    // 添加使用记录
    handleAdd() {
      this.$router.push('/property/parking/usage/add');
    },

    // 编辑使用记录
    handleEdit(row) {
      this.$router.push({
        path: '/property/parking/usage/add',
        query: { id: row.id }
      });
    },

    // 删除使用记录
    handleDelete(row) {
      ElMessageBox.confirm('确定要删除该车位使用记录吗？此操作将不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await axios.delete(`/api/parking-usages/${row.id}`);
          ElMessage.success('删除成功');
          this.fetchParkingUsages();
        } catch (error) {
          console.error('删除车位使用记录失败:', error);
          ElMessage.error('删除车位使用记录失败');
        }
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    },

    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
      }
      
      ElMessageBox.confirm(`确定要删除选中的${this.multipleSelection.length}条记录吗？此操作将不可恢复`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const deletePromises = this.multipleSelection.map(item => 
            axios.delete(`/api/parking-usages/${item.id}`)
          );
          
          await Promise.all(deletePromises);
          ElMessage.success('批量删除成功');
          this.fetchParkingUsages();
        } catch (error) {
          console.error('批量删除失败:', error);
          ElMessage.error('批量删除失败');
        }
      }).catch(() => {
        ElMessage.info('已取消删除');
      });
    },
    
    // 获取使用类型标签
    getUsageTypeTag(type) {
      switch(type) {
        case '购买': return 'success';
        case '租赁': return 'warning';
        case '临时': return 'info';
        default: return '';
      }
    },
    
    // 获取支付状态标签
    getPaymentStatusTag(status) {
      switch(status) {
        case '已支付': return 'success';
        case '未支付': return 'danger';
        case '部分支付': return 'warning';
        default: return '';
      }
    },
    
    // 导出Excel
    async handleExport() {
      try {
        this.exportLoading = true;
        
        // 定义表头
        const header = [
          { label: '所属小区', prop: 'communityName' },
          { label: '车位编号', prop: 'parkingCode' },
          { label: '车位名称', prop: 'parkingName' },
          { label: '业主', prop: 'ownerName' },
          { label: '联系电话', prop: 'ownerPhone' },
          { label: '车牌号', prop: 'carNumber' },
          { label: '使用类型', prop: 'usageType' },
          { label: '起始日期', prop: 'startDate' },
          { label: '结束日期', prop: 'endDate' },
          { label: '费用', prop: 'fee' },
          { label: '支付状态', prop: 'paymentStatus' },
          { label: '备注', prop: 'remarks' }
        ];
        
        // 获取所有数据
        const response = await axios.get('/api/parking-usages/all');
        const data = response.data.map(item => {
          // 格式化日期
          if (item.startDate) {
            item.startDate = this.formatDate(item.startDate);
          }
          if (item.endDate) {
            item.endDate = this.formatDate(item.endDate);
          }
          return item;
        });
        
        // 导出Excel
        ExcelUtil.exportExcel(data, '车位使用记录表', header);
        
        ElMessage.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败: ' + (error.message || '未知错误'));
      } finally {
        this.exportLoading = false;
      }
    },
    
    // 打开导入对话框
    handleImport() {
      this.importDialogVisible = true;
      this.fileList = [];
    },
    
    // 下载导入模板
    async downloadTemplate() {
      try {
        // 创建模板数据
        const templateData = [
          {
            communityName: '阳光花园',
            parkingCode: 'A-101',
            parkingName: 'A区101号',
            ownerName: '张三',
            ownerPhone: '13800138000',
            carNumber: '京A12345',
            usageType: '租赁',
            startDate: '2023-01-01',
            endDate: '2023-12-31',
            fee: '1200',
            paymentStatus: '已支付',
            remarks: '年度租赁'
          }
        ];
        
        // 定义表头
        const header = [
          { label: '所属小区', prop: 'communityName' },
          { label: '车位编号', prop: 'parkingCode' },
          { label: '车位名称', prop: 'parkingName' },
          { label: '业主', prop: 'ownerName' },
          { label: '联系电话', prop: 'ownerPhone' },
          { label: '车牌号', prop: 'carNumber' },
          { label: '使用类型', prop: 'usageType' },
          { label: '起始日期', prop: 'startDate' },
          { label: '结束日期', prop: 'endDate' },
          { label: '费用', prop: 'fee' },
          { label: '支付状态', prop: 'paymentStatus' },
          { label: '备注', prop: 'remarks' }
        ];
        
        // 导出模板
        ExcelUtil.exportExcel(templateData, '车位使用记录导入模板', header);
        
        ElMessage.success('模板下载成功');
      } catch (error) {
        console.error('下载模板失败:', error);
        ElMessage.error('下载模板失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 文件选择变更
    handleFileChange(file) {
      this.fileList = [file];
    },
    
    // 提交导入
    async submitImport() {
      if (!this.fileList.length) {
        ElMessage.warning('请选择要导入的Excel文件');
        return;
      }
      
      try {
        this.importing = true;
        
        // 读取Excel文件
        const file = this.fileList[0].raw;
        
        // 定义表头映射
        const header = [
          { label: '所属小区', prop: 'communityName' },
          { label: '车位编号', prop: 'parkingCode' },
          { label: '车位名称', prop: 'parkingName' },
          { label: '业主', prop: 'ownerName' },
          { label: '联系电话', prop: 'ownerPhone' },
          { label: '车牌号', prop: 'carNumber' },
          { label: '使用类型', prop: 'usageType' },
          { label: '起始日期', prop: 'startDate' },
          { label: '结束日期', prop: 'endDate' },
          { label: '费用', prop: 'fee' },
          { label: '支付状态', prop: 'paymentStatus' },
          { label: '备注', prop: 'remarks' }
        ];
        
        // 解析Excel数据
        const importedData = await ExcelUtil.importExcel(file, header);
        
        // 处理导入数据，查找相关ID
        const processedData = importedData.map(item => {
          // 查找小区ID
          const community = this.communities.find(c => c.name === item.communityName);
          if (community) {
            item.communityId = community.id;
            
            // 查找车位ID
            const parking = this.parkings.find(p => 
              (p.code === item.parkingCode || p.name === item.parkingName) && 
              p.communityId === community.id
            );
            if (parking) {
              item.parkingId = parking.id;
            }
          }
          
          // 转换费用为数字
          if (item.fee) {
            item.fee = parseFloat(item.fee);
          }
          
          return item;
        });
        
        // 提交到后端
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await axios.post('/api/parking-usages/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        ElMessage.success(`导入成功，成功导入${response.data.successCount || importedData.length}条数据`);
        this.importDialogVisible = false;
        this.fetchParkingUsages(); // 刷新列表
      } catch (error) {
        console.error('导入失败:', error);
        ElMessage.error('导入失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.importing = false;
      }
    },

    // 表格选择事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchParkingUsages();
    },

    // 页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchParkingUsages();
    }
  }
};
</script>

<style scoped>
.parking-usage-list-container {
  padding: 20px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title .el-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.header-operations :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 8px 16px;
}

.header-operations :deep(.el-icon) {
  font-size: 18px;
  margin-right: 5px;
}

/* 插图容器样式 */
.illustration-container {
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.illustration-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.illustration-text h3 {
  font-size: 20px;
  color: #409EFF;
  margin: 0 0 8px 0;
}

.illustration-text p {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item__label) {
  font-size: 16px;
}

.search-form :deep(.el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-select .el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 10px 20px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
}

.table-card :deep(.el-table) {
  font-size: 16px;
}

.table-card :deep(.el-table th) {
  font-size: 16px;
  padding: 12px 0;
}

.table-card :deep(.el-table td) {
  padding: 12px 0;
}

.cell-with-icon {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.cell-with-icon .el-icon {
  margin-right: 5px;
  font-size: 18px;
}

.cell-with-icon .el-icon.House {
  color: #67C23A;
}

.cell-with-icon .el-icon.Promotion {
  color: #409EFF;
}

.cell-with-icon .el-icon.Calendar {
  color: #909399;
}

/* 分页样式 */
.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-box :deep(.el-pagination) {
  font-size: 16px;
}

.pagination-box :deep(.el-pagination .el-input__inner) {
  font-size: 16px;
  height: 36px;
}

.pagination-box :deep(.el-pagination button) {
  font-size: 16px;
  min-width: 36px;
  height: 36px;
}

/* 按钮样式调整 */
:deep(.el-button--text) {
  font-size: 16px;
}

:deep(.el-button) {
  font-size: 16px;
}

/* 导入导出相关样式 */
.import-dialog-content {
  padding: 10px 0;
}

.template-download {
  margin-bottom: 20px;
  text-align: center;
}

.excel-upload {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 2px 8px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .illustration-container {
    flex-direction: column;
    text-align: center;
  }
  
  .illustration-image {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>